<?php

define('IN_MOBILE', 4);
define('IN_NEWMOBILE', true);

if(!checkmobile() || $_GET['mobile']==4){
    $currurl = currenturl_231();
    if($_GET['tid']){
        $currurl = 'forum.php?mod='.$_GET['a'].'&tid='.$_GET['tid'];
        dheader("Location: ".$currurl);
    }else if($_GET['fid']){
        $currurl = 'forum.php?mod=forumdisplay&fid='.$_GET['fid'];
        dheader("Location: ".$currurl);
    }
}
global $_G;

$_G['wechat']['setting'] = unserialize($_G['setting']['mobilewechat']);
$config = $_G['cache']['plugin']['xigua_wsq'];
if($_GET['a'] =='login' || ($_GET['login'] == 'yes' && !$_G['uid'])){
    if($config['loginpage']!=1){
        dheader("Location: ".$_G['siteurl'].'member.php?mod=logging&action=login&mobile=2&referer='.urlencode($_GET['referer']));
    }
}
if(!$_G['uid']){
    $inwchat = (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false);
    $xigua_loginconfig = $_G['cache']['plugin']['xigua_login'];
    if(
        !$_G['cookie']['widthauto'] &&
        $xigua_loginconfig['openautologin'] &&
        $inwchat &&
        CURSCRIPT!='member' &&
        CURSCRIPT!='check' &&
        !$_G['inajax']&&
        !defined('IN_MOBILE_API')
        &&!$_GET['version']
    ){
        dsetcookie('widthauto', 1, 864000);
        dheader("Location: ".$_G['siteurl'].'plugin.php?id=xigua_login:login&backreferer='.urlencode(currenturl_231()));
    }

}
if($_GET['a'] == 'forumlist' && $_G['cache']['plugin']['xigua_logo']){
    dheader('Location: '. $_G['siteurl'] . 'plugin.php?id=xigua_logo:forumlist');
}
if($_GET['a'] == 'profile' && !$_GET['uid'] && !$_G['uid']){
    dheader('Location: '. $_G['siteurl']);
}

$wbconfig = $_G['cache']['plugin']['xigua_weban'];
$_G['tid'] = $_G['tid'] ? $_G['tid'] : intval($_GET['tid']);
$_G['fid'] = $_G['fid'] ? $_G['fid'] : intval($_GET['fid']);
if(!$_G['fid']){
    $f = C::t('forum_thread')->fetch($_G['tid']);
    $_G['fid'] = $f['fid'];
}
$frompyq = isset($_GET['isappinstalled']);
if (
!(!$wbconfig['mobiletid'] || !in_array($_G['fid'], unserialize($wbconfig['fids']))) &&
!($wbconfig['onlywx'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false) &&
!($wbconfig['isappinstalled']&&!$frompyq) &&
!(($_GET['aid'] && !$frompyq) ||  $_GET['from'] ||  $_G['forum_thread']['special'] || $_GET['version'] ||$GLOBALS['RUNS'])
){
    if($_GET['a'] =='index' && $wbconfig['wsq']){
        dheader("Location: $_G[siteurl]forum.php?mod=forumdisplay&drewb=1&fid=$_G[fid]");
    }elseif ($_GET['a'] == 'viewthread' && $wbconfig['wsqtid']){
        dheader("Location: $_G[siteurl]forum.php?mod=viewthread&drewb=1&tid=$_G[tid]");
    }
}

//chdir('../');
//require_once './source/class/class_core.php';
//
//$discuz = C::app();
//
//$discuz->reject_robot();
//$discuz->init_cron = false;
//$discuz->init_session = false;
//$discuz->init_user = false;
//$discuz->init_mobile = false;
//
//$discuz->init();

if ($_GET['c'] == 'static') {
    $path = DISCUZ_ROOT . 'source/plugin/xigua_wsq/template/touch/m/js/';
    $bpath = DISCUZ_ROOT . 'source/plugin/xigua_wsq/template/touch/m/js/';
    header("Content-type: application/json");
    $files = explode(',', $_GET['f']);
    $version = $_GET['v'];
    $cachename = 'static_' . md5($_GET['f']) . $version;
    if (!$files) {
        $array = array('code' => 1);
        echo json_encode($array);
        exit;
    }
    $contents = array();
    foreach ($files as $file) {
        if (strpos($file, '..') !== false) {
            continue;
        }
        $filename = file_exists($path . $file) ? $path . $file : $bpath . $file;
        $contents[$file] = file_get_contents($filename);
    }
    $array = array('code' => 0, 'file' => $contents);
    $result = json_encode($array);
    echo $result;
    exit;
}

$jsglobal = array(
    'source' => '',
    'cookiepre' => $discuz->config['cookie']['cookiepre'],
    'jsversion' => $_G['style']['verhash'],
    'f' => '',
    'path' => '',
    'formhash' => FORMHASH,
    'plugins' => array()
);

$wechat = unserialize($_G['setting']['mobilewechat']);
$logo = $wechat['wsq_sitelogo'];
$site = array(
    'siteId' => 0,
    'siteUrl' => $_G['siteurl'],
    'siteName' => diconv($_G['setting']['sitename'], CHARSET, 'UTF-8'),
    'siteLogo' => $logo ? $logo : $_G['siteurl'] . '/static/image/common/logo.png',
);

$a = $_GET['a'] && preg_match('/^\w+$/', $_GET['a']) ? $_GET['a'] : 'index';

switch ($a){
    case 'profile':
        $navheader = lang('home/template', 'personal_main_page');
        break;
    case 'mypm':
        $navheader = lang('template', 'notice_pm');
        break;
    case 'mynotice':
        $navheader = lang('plugin/xigua_wsq', 'm_my_ntc');
        break;
    case 'mythread':
        if($_GET['ac'] =='reply'){
            $navheader = lang('plugin/xigua_wsq', 'm_my_r');
        }else if($_GET['ac']=='thread'){
            $navheader = lang('plugin/xigua_wsq', 'm_my_t');
        }
        break;
}

if($tid = intval($_GET['tid'])){

    $thread = C::t('forum_thread')->fetch($tid);
    $navheader = $thread['subject'];
	$replace_aimg = '';


    $arow = DB::fetch_first("SELECT a.aid,a.tableid from %t as a where a.tid=%d AND tableid!=127 ORDER BY aid ASC LIMIT 1", array( 'forum_attachment', $tid ));
    if($arow){
        $table = DB::table('forum_attachment_' . intval($arow['tableid']));
        $aid = $arow['aid'];
        $row = DB::fetch_first("SELECT attachment,remote FROM $table WHERE aid='$aid' AND isimage IN(-1, 1) LIMIT 1");
        if ($row['attachment']) {
            $replace_aimg = get_picurl231($row['attachment'], $row['remote']);
        }
    }

    $message = DB::result_first( 'SELECT message FROM %t WHERE tid=%d AND first=1  AND invisible=0 LIMIT 1', array(table_forum_post::get_tablename('tid:' . $tid), $tid) );
    if( !$replace_aimg)
    {
		if(strpos($message, '[/img]') !== FALSE ){
			$pattern = "/\[img.*?\](.*?)\[\/img\]/i";
			preg_match_all($pattern, $message, $matchsimg);
			if($matchsimg[1]){
				$replace_aimg = $matchsimg[1][0];
			}
		}
    }
    $sppos = strpos($message, chr(0).chr(0).chr(0));
    if($sppos !== false) {
        $message = substr($message, 0, $sppos);
    }
    $message = preg_replace(array(lang('forum/misc', 'post_edit_regexp'), lang('forum/misc', 'post_edithtml_regexp'), lang('forum/misc', 'post_editnobbcode_regexp')), '', $message);
    if(strpos($message, '[/hide]') !== FALSE){
        $message = preg_replace('/\[hide\].*?\[\/hide\]/i', '', $message);
    }

    $pattern = "/(\[attach(img)?\]|\[(img|url|media|audio|flash)(.*)\]).*?(\[\/attach(img)?\]|\[\/(img|url|media|audio|flash)\])/i";
    $message = preg_replace($pattern, '', $message);
    $message = str_replace(array('&nbsp;', '&amp;', '&quot;', '&lt;', '&gt;', '[', ']'), array('', '', '', '', '', '<', '>'), $message);
    $message = strip_tags($message);
    $message = cutstr($message, 100);

    $replace_aimg = $replace_aimg ? $replace_aimg : $_G['wechat']['setting']['wsq_sitelogo'];
    $sharhtml = get_share_231($config['appid'], $config['appsecret'], $config['debug'], $replace_aimg, $message, $navheader);
}else if($_GET['fid'] = intval($_GET['fid'])){

    if(empty( $_G['cache']['forums'])){
        loadcache('forums');
    }
    $forums = $_G['cache']['forums'][$_GET['fid']];

    $_G['wechat']['setting'] = unserialize($_G['setting']['mobilewechat']);
    $dindex = intval($_G['wechat']['setting']['wsq_fid']);
    if($dindex != $_GET['fid']){
        include_once libfile('function/forumlist');
        $navheader = $forums['name'];
        $replace_aimg = $_G['wechat']['setting']['wsq_sitelogo'];

        $forum = C::t('forum_forum')->fetch($_GET['fid']);
        $replace_aimg = get_forumimg($forum['icon']);
        $desc = ($forum['descriptionnew']);
    }

    $navheader    = $navheader ? $navheader : $_G['wechat']['setting']['wsq_sitename'];
    $replace_aimg = $replace_aimg ? $replace_aimg : $_G['wechat']['setting']['wsq_sitelogo'];
    $desc         = $desc ? $desc : $_G['wechat']['setting']['wsq_sitesummary'];

    $sharhtml = get_share_231($config['appid'], $config['appsecret'], $config['debug'], $replace_aimg, $desc, $navheader);
}

include template('xigua_wsq:m/' . $a);





function get_picurl231($pic, $remote = 0){
    global $_G;
    if(!$pic){
        return '';
    }
    if(is_picurl231($pic)){
        return $pic;
    }

    if($remote){
        $attach__ = $_G['setting']['ftp']['attachurl'] . 'forum/' . $pic;
    }else{
        $pic = $_G['setting']['attachurl'].'forum/'.$pic;
        if(is_picurl231($pic)){
            return $pic;
        }
        $attach__ = $_G['siteurl'].$pic;
    }
    return $attach__;
}
function is_picurl231($pic){
    return in_array(strtolower(substr($pic, 0, 6)), array('http:/', 'https:', 'ftp://'));
}

function currenturl_231($related = 0) {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    return $related ? $relate_url : $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}


function get_signature_231($appid,$appsecret, $noncestr, $acurl, $timestamp)
{
    if(empty($appid) || empty($appsecret)){
        return '';
    }
    $key1 = md5($appid.$appsecret);
    $key2 = 't'.$key1;

    if(! $ret = readcache_231($key1)){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $ret = file_get_contents($url);
        $ret = json_decode($ret, TRUE);
        writecache_231($key1, $ret, $ret['expires_in']);
    }
    $access_token = $ret['access_token'];

    if(! $ret = readcache_231($key2)) {
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        $ret = file_get_contents($url);

        $ret = json_decode($ret, TRUE);
        if($ret['errcode'] == 0){
            writecache_231($key2, $ret, $ret['expires_in']);
        }
    }
    $string1 = "jsapi_ticket=$ret[ticket]&noncestr=$noncestr&timestamp=$timestamp&url=$acurl";

    $signature = sha1( $string1 );
    return $signature;
}


function writecache_231($script, $array = array(), $expirein = 7200)
{
    $expirein = $expirein - 100;
    $datas = array(
        'expireat' => time()+$expirein,
        'data'     => $array
    );
    $cachedata = " return ".var_export($datas, true).";";

    global $_G;

    $dir = DISCUZ_ROOT.'./source/plugin/xigua_wsq/cache/';
    if(!is_dir($dir)) {
        dmkdir($dir, 0777);
    }
    if($fp = @fopen("$dir$script.php", 'wb')) {
        fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!\n//Identify: ".md5($script.'.php'.$cachedata.$_G['config']['security']['authkey'])."\n\n$cachedata?>");
        fclose($fp);
    } else {
        exit('Can not write to cache files, please check directory ./source/plugin/xigua_wsq/cache/ .');
    }
}

function readcache_231($script)
{
    $dir = DISCUZ_ROOT.'./source/plugin/xigua_wsq/cache/';
    if(!is_dir($dir)) {
        dmkdir($dir, 0777);
    }

    $ret = array();

    if(is_file("$dir$script.php")){
        $rets =  include "$dir$script.php";
        $ret = $rets['data'];
        if(time()>= $rets['expireat'] )
        {
            $ret = array();
        }
    }
    return $ret;
}
function filter_desc_231($desc){
    return str_replace(array(
        '\'',"\n","\r","\t"
    ), '', $desc);
}

function get_share_231($appid, $appsecret, $debug, $img, $desc, $title){
    $ret = '';
    $timestamp  = time();
    $noncestr   = uniqid('wx');
    $currenturl = currenturl_231();
    $signature  = (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) ? get_signature_231($appid, $appsecret, $noncestr, $currenturl, $timestamp) : '';
    $debug = $debug ? 'true':'false';
    $desc= trim(strip_tags(str_replace(array("\n", "\r", "\t"), '', $desc)));
    $link= currenturl_231();

    if($signature){
        $ret = "<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script><script>
setTimeout(function(){
wx.config({debug:$debug,appId: '$appid', timestamp:$timestamp, nonceStr:'$noncestr', signature:'$signature',jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo']
});
wx.ready(function () {
    var imgUrl = '$img';
    var desc = '$desc';
    var title = '$title';
    var link = '$link';
    wx.onMenuShareAppMessage({ title: title, desc: desc, link: link,imgUrl: imgUrl});
    wx.onMenuShareTimeline({ title: title, link: link, imgUrl: imgUrl});
    wx.onMenuShareQQ({title: title,desc: desc,link: link,imgUrl: imgUrl});
    wx.onMenuShareWeibo({title: title, desc: desc, link: link, imgUrl: imgUrl});
});
},1000);
</script> <img src='$img' style='position:absolute;top:-100000px;height:800px;width:800px;' /> ";
    }else{
        $ret = "<img src='$img' style='position:absolute;top:-100000px;height:800px;width:800px;' />";
    }
    return $ret;
}
/*
wx.ready(function () {
    wx.onMenuShareAppMessage({ title: title, desc: desc, link: link,imgUrl: imgUrl});
    wx.onMenuShareTimeline({ title: title, link: link, imgUrl: imgUrl});
    wx.onMenuShareQQ({title: title,desc: desc,link: link,imgUrl: imgUrl});
    wx.onMenuShareWeibo({title: title, desc: desc, link: link, imgUrl: imgUrl});
});*/